from django.shortcuts import render
from django.shortcuts import HttpResponse
from repoistory import models
from django.http import Http404

import json

from .libs.forms import ActionForm
from .libs import actions

# Create your views here.

def index(request):
    '''首页'''
    return render(request,'index.html')


def preview(request):
    '''总览'''
    res_dict = {'query_set': models.Project.objects.all().values('id', 'name', 'description')}
    return render(request, 'web/index.html', res_dict)


def version_control(request, nid):
    '''版本管理'''
    project_obj = models.Project.objects.filter(id=nid).prefetch_related('submodul_set').first()
    all_project = models.Project.objects.all()
    if not project_obj:
        raise Http404
    if request.method == 'GET':
        form_obj = ActionForm(project_id=project_obj.id)
        res_dict = {'project': project_obj,
                    'all_project': all_project,
                    'form_obj': form_obj,
                    'query_set': models.SubModul.objects.filter(project=project_obj).order_by('order').values('id','name','description')}
        return render(request,'web/console.html',res_dict)
    elif request.method == 'POST':
        res_dict = {'status': True, 'error': None, 'data': None}
        if not request.POST.get('action'):
            res_dict['status'] = False
            res_dict['error'] = '请选择要执行的操作'
        elif not hasattr(actions,request.POST.get('action')):
            res_dict['status'] = False
            res_dict['error'] = '系统繁忙，请稍候再试'
        elif request.POST.get('action') !='build' and not request.POST.get('selected_ids'):
                res_dict['status'] = False
                res_dict['error'] = '至少选择一个子模块'
        else:
            action = getattr(actions,request.POST.get('action'))
            branch = request.POST.get('branch').strip() if request.POST.get('branch').strip() != '' else 'master'
            selected_ids = request.POST.get('selected_ids')
            # action(project_obj=project_obj, branch=branch, selected_ids=selected_ids)
            try:
                action(project_obj=project_obj,branch=branch,selected_ids=selected_ids)
            except Exception as e:
                res_dict['status'] = False
                res_dict['error'] = e.__str__()
        return HttpResponse(json.dumps(res_dict))
